package net.chenlin.dp.ids.client.util;

import net.chenlin.dp.ids.common.util.CommonUtil;

/**
 * 敏感信息隐位工具类
 * @author zhouchenglin[yczclcn@163.com]
 */
public class MaskUtil {

    /** 邮箱最小长度 */
    private static final int EMAIL_MIN_LEN = 2;

    private MaskUtil() {}

    /**
     * 邮箱隐位
     * @param email
     * @return
     */
    public static String maskEmail(String email) {
        if (!ValidateUtil.isEmail(email)) {
            return email;
        }
        int index = email.indexOf("@");
        String emailAccount = email.substring(0, index);
        int accountLength = emailAccount.length();
        String accountPrefix;
        String accountSuffix = emailAccount.substring(accountLength - 1);
        if (accountLength < EMAIL_MIN_LEN) {
            accountPrefix = emailAccount + emailAccount;
        } else {
            accountPrefix = emailAccount.substring(0, EMAIL_MIN_LEN);
        }
        return String.format("%s%s%s%s", accountPrefix, "***", accountSuffix, email.substring(index));
    }

    /**
     * 手机号隐位
     * @param mobile
     * @return
     */
    public static String maskMobile(String mobile) {
        if (!ValidateUtil.isMobile(mobile)) {
            return mobile;
        }
        String mobilePrefix = mobile.substring(0, 3);
        String mobileSuffix = mobile.substring(9);
        return String.format("%s%s%s", mobilePrefix, "****", mobileSuffix);
    }

    /**
     * 名称隐位
     * @param name
     * @return
     */
    public static String maskName(String name) {
        if (CommonUtil.strIsNotEmpty(name)) {
            return "*" + name.substring(1);
        }
        return name;
    }

    /**
     * 银行卡号隐位
     * @param bankCardNo
     * @return
     */
    public static String maskBankCard(String bankCardNo) {
        if (ValidateUtil.isBankCardNo(bankCardNo)) {
            return "***" + bankCardNo.substring(bankCardNo.length() - 4);
        }
        return bankCardNo;
    }

    /**
     * 用户登录名隐位
     * @param userAlias
     * @return
     */
    public static String maskUserAlias(String userAlias) {
        if (CommonUtil.strIsNotEmpty(userAlias)) {
            if (ValidateUtil.isEmail(userAlias)) {
                return maskEmail(userAlias);
            }
            if (ValidateUtil.isMobile(userAlias)) {
                return maskMobile(userAlias);
            }
        }
        return userAlias;
    }

}
